<script setup>
import { ref } from 'vue'
import { editCheckType, addCheckType } from '@/api/checkType'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const emits = defineEmits(['query'])

const formData = ref({
  id: null,
  code: null, 
  name: null, 
  description: null, 
  status: 1 
})

const save = async() => {
  if (!formData.value.code) {
    ElMessage.warning('请输入检验类型编码')
    return
  }
  if (!formData.value.name) {
    ElMessage.warning('请输入检验类型名称')
    return
  }

  try {
    if (formData.value.id) {
      await editCheckType(formData.value)
      ElMessage.success('修改成功！')
    } else {
      await addCheckType(formData.value)
      ElMessage.success('新增成功！')
    }
    dialogVisible.value = false
    emits('query')
    formData.value = { id: null, code: null, name: null, description: null, status: 1 }
  } catch (error) {
    ElMessage.error('操作失败：' + (error.message || '网络错误'))
  }
}

const handleClose = () => {
  formData.value = { id: null, code: null, name: null, description: null, status: 1 }
  dialogVisible.value = false
}

defineExpose({
  formData,
  dialogVisible
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formData.id ? '编辑检验类型' : '新增检验类型'"
    width="500"
    :before-close="handleClose"
  >
    <el-form :model="formData" label-width="100px" style="max-width: 600px">
      <el-form-item label="类型编码" prop="code" required>
        <el-input v-model="formData.code" placeholder="请输入检验类型编码" />
      </el-form-item>
      
      <el-form-item label="类型名称" prop="name" required>
        <el-input v-model="formData.name" placeholder="请输入检验类型名称" />
      </el-form-item>
      
      <el-form-item label="类型描述">
        <el-input
          v-model="formData.description"
          placeholder="请输入检验类型描述"
          type="textarea"
          rows= 3
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>